package com.lishu.carsafe.activity;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.lishu.carsafe.R;
import com.lishu.carsafe.http.HttpBase;
import com.lishu.carsafe.http.HttpLoader;
import com.lishu.carsafe.listener.UploadFileListener;
import com.lishu.carsafe.model.BaseModel;
import com.lishu.carsafe.model.ScheduleSignInfoModel;
import com.lishu.carsafe.model.ScheduleSignInfoModel.ScheduleSignInfoBean;
import com.lishu.carsafe.model.UploadFileModel;
import com.lishu.carsafe.utils.DateSearchUtil;
import com.lishu.carsafe.utils.ImageUtil;
import com.lishu.carsafe.utils.LogUtil;
import com.lishu.carsafe.utils.NetUtil;
import com.lishu.carsafe.utils.ToastUtil;

import java.io.File;

/**
 * describe:
 *
 * @author:ZhangWei(张伟) date:2020/5/22
 * time:17:22
 * motto:高山仰止，景行行止，虽不能至，心向往之。
 */
public class SignInActivity extends BaseActivity {
    //是否是查看详情
    public static final String IS_DETAIL = "isDetails";
    //排班id
    public static final String SCHEDULE_ID = "schedule_id";

    private ImageView iv_sign_photo_hint, iv_sign_photo, iv_sign_local;
    private TextView tv_sign_local, tv_sign_address, tv_sign_time, tv_sign_ok;
    private LocationClient mLocationClient;
//    private MyLocationData locData;
    private GeoCoder mCoder;
    private boolean isLocal = false;//true表示重新定位 第一次为true
    private int id;//排版id
    private String signAddress, signTime;

    //拍照
    private String localImageUrl;
    private String uploadedMediaUrl;
    private File cameraFile;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_in);

        requestPermission();

        initView();
        isLocal = true;
        initEvent();
        initData();
    }

    private void initView() {
        setTopTitle("签到");
        iv_sign_photo_hint = findViewById(R.id.iv_sign_photo_hint);
        iv_sign_photo = findViewById(R.id.iv_sign_photo);
        iv_sign_local = findViewById(R.id.iv_sign_local);
        tv_sign_local = findViewById(R.id.tv_sign_local);
        tv_sign_address = findViewById(R.id.tv_sign_address);
        tv_sign_time = findViewById(R.id.tv_sign_time);
        tv_sign_ok = findViewById(R.id.tv_sign_ok);
    }

    private void initData() {
        Intent intent = getIntent();
        boolean isDetail = intent.getBooleanExtra(IS_DETAIL, false);
        id = intent.getIntExtra(SCHEDULE_ID,0);
        if (isDetail) {
            //是详情 隐藏很多控件 并放开图片
            iv_sign_photo_hint.setVisibility(View.GONE);
            iv_sign_local.setVisibility(View.GONE);
            tv_sign_local.setVisibility(View.GONE);
            tv_sign_ok.setVisibility(View.GONE);
            iv_sign_photo.setVisibility(View.VISIBLE);
            //请求服务器地址并加载网络图片
            querySignIn();
        } else {
            //非详情界面的情况下 做定位
            initMap();
            iv_sign_photo.setVisibility(View.GONE);
        }
    }

    private void initEvent() {
        iv_sign_photo_hint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //选择照片和拍照
                checkPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
            }
        });

        //点击确定 点击签到
        tv_sign_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signAddress = tv_sign_address.getText().toString();
                signTime = tv_sign_time.getText().toString();
                if(iv_sign_photo_hint.getVisibility() == View.VISIBLE){
                    ToastUtil.showShort("请拍摄签到照片");
                    return;
                }
                showAlways("上传中，请稍后...");
                sendPicture(localImageUrl);
            }
        });
    }

    /**
     * 获取签到
     */
    public void querySignIn(){
        showAlways("正在加载，请稍等");
        HttpLoader.scheduleSignInfo(id+"", new HttpBase.IResponseListener() {
            @Override
            public void onResponse(BaseModel model) {
                hide();
                if (model == null) {
                    ToastUtil.showShort(R.string.please_check_network);
                    return;
                }
                if (!model.success()) {
                    ToastUtil.showShort(getString(R.string.get_data_fail) + model.getMsg());
                    return;
                }
                ScheduleSignInfoBean infoBean = ((ScheduleSignInfoModel)model).getData();
                //更新界面
                ImageUtil.bindImageView(iv_sign_photo, NetUtil.getFullPath(infoBean.getSignImgUrl()), R.drawable.ic_default_photo);
                tv_sign_address.setText(infoBean.getSignAddress());
                tv_sign_time.setText(infoBean.getSignTime());
            }
        });
    }

    //重新定位
    public void onLoc(View view) {
        //重新定位的代码
        isLocal = true;
        //弹出加载框 定位成功后取消加载框

    }

    private void initMap() {
        //定位初始化
        mLocationClient = new LocationClient(this);

        //通过LocationClientOption设置LocationClient相关参数
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);//如果为0 定位一次

        //设置locationClientOption
        mLocationClient.setLocOption(option);

        //注册LocationListener监听器
        MyLocationListener myLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myLocationListener);
        //开启地图定位图层
        mLocationClient.start();

        mCoder = GeoCoder.newInstance();
        mCoder.setOnGetGeoCodeResultListener(listener);
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null) {
                return;
            }
//            locData = new MyLocationData.Builder()
//                    .accuracy(location.getRadius())
//                    // 此处设置开发者获取到的方向信息，顺时针0-360
//                    .direction(location.getDirection()).latitude(location.getLatitude())
//                    .longitude(location.getLongitude()).build();
            if(isLocal){
                isLocal = false;
                LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
                mCoder.reverseGeoCode(new ReverseGeoCodeOption()
                        .location(latLng)
                        // POI召回半径，允许设置区间为0-1000米，超过1000米按1000米召回。默认值为1000
                        .radius(500));
            }
        }
    }

    //检索地址
    OnGetGeoCoderResultListener listener = new OnGetGeoCoderResultListener() {

        @Override
        public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

        }

        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
            if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
                //没有找到检索结果
                isLocal  = true;
                return;
            } else {
                //详细地址
                String address = reverseGeoCodeResult.getAddress();
                if(reverseGeoCodeResult.getPoiRegionsInfoList() != null && reverseGeoCodeResult.getPoiRegionsInfoList().size() > 0){
                    address = reverseGeoCodeResult.getPoiRegionsInfoList().get(0).getRegionName();
                }
                tv_sign_time.setText(DateSearchUtil.getCurrentDateTime());
                tv_sign_address.setText(address);
            }
        }
    };

    protected void onRequestPermissionsGranted(int requestCode) {
        if (requestCode == 100) {
            checkPermissions(new String[]{Manifest.permission.CAMERA}, 101);
        }else if(requestCode == 101){
            selectPicFromCamera();
        }
    }

    /**
     * 通过照相得到照片
     */
    public void selectPicFromCamera() {
        if (!(android.os.Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED))) {
            Toast.makeText(getApplicationContext(), "SD卡不存在，不能拍照",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/safe");
        if(!dir.exists()){
            dir.mkdir();
        }
        cameraFile = new File(dir, System.currentTimeMillis() + ".jpg");
        LogUtil.d("TaskDisposeActivity cameraFile1 = " + cameraFile);

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if(Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(this, "com.lishu.carsafe.fileprovider", cameraFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, apkUri);
        }else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
        }
        startActivityForResult(intent, 99);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK && requestCode == 99){
            if (cameraFile != null && cameraFile.exists()){
                try {
                    //1、得到新拍的照片
                    localImageUrl = cameraFile.getAbsolutePath();
                    LogUtil.d("sendFileLocalPath="+localImageUrl);
                    //2.1、压缩图片
                    //2.2、加入List
                    //3、更新显示
                    ImageUtil.bindImageView(iv_sign_photo, localImageUrl, R.drawable.ic_default_photo);
                    iv_sign_photo.setVisibility(View.VISIBLE);
                    iv_sign_photo_hint.setVisibility(View.GONE);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void sendPicture(String imgPath) {
        HttpLoader.uploadFile("handle", imgPath, new HttpBase.IResponseListener() {
            @Override
            public void onResponse(BaseModel model) {
                if (model == null) {
                    hide();
                    ToastUtil.showShort(R.string.please_check_network);
                    return;
                }
                if (!model.success()) {
                    hide();
                    ToastUtil.showShort(getString(R.string.get_data_fail) + model.getMsg());
                    return;
                }
                UploadFileModel uploadFileModel = (UploadFileModel) model;
                if (uploadFileModel != null) {
                    uploadedMediaUrl = uploadFileModel.getData();
                }

                submitSignIn(uploadedMediaUrl);
            }
        });
    }

    /**
     * 签到提交到服务器
     * @param uploadedMediaUrl
     */
    private void submitSignIn(String uploadedMediaUrl){
        HttpLoader.scheduleSignIn(id+"",signAddress, signTime, uploadedMediaUrl, new HttpBase.IResponseListener() {
            @Override
            public void onResponse(BaseModel model) {
                hide();
                if (model == null) {
                    ToastUtil.showShort(R.string.please_check_network);
                    return;
                }
                if (!model.success()) {
                    ToastUtil.showShort(getString(R.string.get_data_fail) + model.getMsg());
                    return;
                }
                //返回上一个界面
                finish();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCoder != null){
            mCoder.destroy();
        }
        if(mLocationClient != null){
            mLocationClient.stop();
        }
    }
}
